<!--实时通信-->
<template>
  <div class="communicateConatiner">
    <CommonBar :options="options"></CommonBar>
    <!--回话记录开始-->
    <div class="content">
      <div v-for="(item,index) in commuteList" :key="index" @click="playo(item,index)">
        <audio :ref="'middle'+ index">
          <source :src="item.audio_path" type="audio/mpeg" />
        </audio>
        <p class="time">{{item.message_date}}</p>
        <div class="hediv" v-if="item.uid!==user_id">
          <van-image
            v-if="item.photo"
            round
            width="45px"
            height="45px"
            :src="`http://www.kdehw.com:83/uploads/images/user/${item.photo}`"
            fit="cover"
            class="txphoto"
          />
          <p class="txphoto1" v-else>{{substringname(item.name)}}</p>
          <p class="communicatedialog">
            <van-image
              v-if="item.isplay==false"
              width="17px"
              height="20px"
              :src="item.viewimg"
              fit="cover"
              class="txphoto"
            />
            <van-image
              v-else
              width="17px"
              height="20px"
              :src="myicongif"
              fit="cover"
              class="txphoto"
            />
            <span>{{item.seconds}}</span>
          </p>
        </div>
        <div class="mydiv" v-else>
          <p class="communicatedialog">
            <span class="muspan">{{item.seconds}}</span>
            <van-image
              v-if="item.isplay==false"
              round
              width="17px"
              height="20px"
              :src="item.viewimg"
              fit="cover"
              class="txphoto"
            />
            <van-image
              v-if="item.isplay==true"
              width="17px"
              height="20px"
              :src="hesicongif"
              fit="cover"
              class="txphoto"
            />
          </p>
          <van-image
            v-if="item.photo"
            round
            width="45px"
            height="45px"
            :src="`http://www.kdehw.com:83/uploads/images/user/${item.photo}`"
            fit="cover"
            class="txphoto"
          />
          <p class="txphoto1" v-else>{{substringname(item.name)}}</p>
        </div>
      </div>
    </div>
    <!--回话记录结束-->
    <!-- <input type="button" value="录音播放" id="luyin_bofang" @click="playAudio(recordFile)" /> -->
    <!-- 中间黑框 录音状态 -->
    <div class="blackBoxSpeak" v-show="blackBoxSpeak">
      <div class="blackBoxSpeak-flex">
        <van-image :src="ic_record" class="ic_record" />
        <van-image :src="ic_record_ripple" class="ic_record_ripple" />
      </div>
      <p class="blackBoxSpeakConent">手指上划，取消发送</p>
    </div>

    <!-- 中间黑框 暂停状态 -->
    <div class="blackBoxPause" v-show="blackBoxPause">
      <div class="blackBoxSpeak-flex">
        <van-image :src="ic_record_cancle" class="ic_record_cancle" />
      </div>
      <p class="blackBoxPauseContent" style="background: red">松开手指， 取消发送</p>
    </div>
    <!-- 按住说话按钮状态 -->
    <div
      class="buttontext"
      :class="buttonback==true?'buttontexthui':''"
      @touchstart="gotouchstart"
      @touchmove="gotouchmove"
      @touchend="gotouchend"
    >{{buttontext}}</div>
  </div>
</template>
<script>
var timeOutEvent = 0;
//手指移动相关
var posStart = 0; //初始化起点坐标
var posEnd = 0; //初始化终点坐标
var posMove = 0; //初始化滑动坐标
var my_media = null;
import { getFileContentAsBase64 } from "../common/compressImage";
import CommonBar from "../common/commonBar";
import { mapState } from "vuex";
export default {
  data() {
    return {
      ic_record: require("../../../static/image/ic_record.png"),
      ic_record_ripple: require("../../../static/image/ic_record_ripple.png"),
      ic_record_cancle: require("../../../static/image/ic_release_to_cancel.png"),
      hesicon: require("../../../static/image/hesicon.png"),
      hesicongif: require("../../../static/image/myicongif.gif"),
      myicon: require("../../../static/image/myicon.png"),
      myicongif: require("../../../static/image/heisicongif.gif"),
      options: {
        type: "icon",
        centerText: "会话记录",
        iconNname: "wap-home",
        lefttype: "left"
      },
      mediaRec: "",
      recTimeMax: 20,
      recTime: 0,
      buttontext: "按住说话",
      timeOutEvent: 0,
      recordstatus: false,
      file: "",
      platform: "",
      channelId: "",
      buttonback: false,
      blackBoxSpeak: false,
      blackBoxPause: false,
      recordSuccess: false,
      uploadaudio: 0,
      recordFile: "name.wav",

      commuteList: [],
      audiostatus: 0,
      audio: "",
      url: "",
      timer: null,
      isPlaying: false,
      currentTime: 0,
      duration: "",
      currentAudioId: "", //当前语音id
      audiolength: 0,
      ins: 0
    };
  },
  components: {
    CommonBar
  },
  computed: {
    ...mapState({
      token: state => state.Authorization,
      user_id: state => state.userData.id
    })
  },
  created() {
    this.channelId = this.$route.query.channel_no;
  },
  mounted() {
    this.GetHistoryList();
  },
  //当拍照改变后photo数组就为空
  watch: {
    audio(newval, oldval) {
      if (newval != oldval) {
        // console.log("两个播放器不相等");
        // console.log(typeof oldval);
        oldval.pause();
        oldval.currentTime = 0;
        newval.currentTime = 0;
        newval.play();
      } else {
        // console.log("两个播放器相等");
      }
    },
    //通过索引判断动画
    ins: {
      handler: function(newVal, oldval) {
        //console.log(this.commuteList[oldval].isplay);
        if (this.commuteList[oldval].isplay == true) {
          this.commuteList[oldval].isplay = false;
        }
      },
      deep: true //深度监听
    }
  },
  methods: {
    //取头像
    substringname(username) {
      if (username) {
        if (username.length >= 3) {
          return username.substr(username.length - 2, 2);
        } else {
          return username;
        }
      }
    },
    //时间转换
    substringtime(seconds) {
      if (seconds) {
        if (seconds < 60) {
          return Math.round(seconds) + "''";
        } else {
          seconds = Math.round(seconds);
          var muinte = seconds / 60;
          console.log(muinte);
          var miao = seconds % 60;
          console.log(miao);
          if (miao == 0) {
            return muinte + " ' ";
          } else {
            return muinte + " ' " + miao + "''";
          }
        }
      }
    },
    //获取总时间
    substringTime(str) {
      if (str) {
        str = str.split(" ")[1];
        return str.substring(0, str.length - 3);
      }
    },
    //拿历史数据
    GetHistoryList() {
      var that = this;
      that.$toast.loading({
        mask: true,
        message: "加载中...",
        duration: 5000
      });
      var params = {
        id: that.channelId,
        token: that.token
      };
      that.$http
        .get(
          `${that.$basePath}?service=App.AudioData.GetAudioHistoryData&api=96`,
          {
            params: params
          }
        )
        .then(res => {
          if (res.ret == 200) {
            that.$toast.clear();
            console.log("历史记录", res);
            var list = res.data;
            that.commuteList = list.map(function(obj, index) {
              obj.isplay = false; //添加id属性
              if (obj.uid != that.user_id) {
                obj.viewimg = that.myicon;
              } else {
                obj.viewimg = that.hesicon;
              }
              return obj; //如果不返回则输出： Array [undefined, undefined, undefined
            });
            console.log("新建历史数据", that.commuteList);
          } else {
            that.$toast({ message: res.msg });
          }
        });
    },
    //播放语音
    playo(item, index) {
      var that = this;
      that.ins = index;
      //console.log(that.commuteList[index]);
      that.audio = "middle" + index;
      //console.log(that.audio);
      that.audio = that.$refs[that.audio][0];
      //console.log(that.audio, item.src);
      // let audio = that.$refs.audio;
      that.duration = that.audio.duration;
      //console.log(that.duration);
      if (!that.commuteList[index].isplay) {
        //console.log("播放");
        that.audio.play();
        that.commuteList[index].isplay = true;
        //切换为动画效果
        that.timer = setTimeout(() => {
          that.commuteList[index].isplay = false;
        }, that.duration * 1000);
      } else {
        console.log("暂停");
        that.audio.pause();
        clearTimeout(that.timer);
        that.commuteList[index].isplay = false;
        that.audio.currentTime = 0;
      }
    },
    //长按事件
    gotouchstart(event) {
      // console.log("开始");
      // let that = this;
      // event.preventDefault();
      // posStart = 0;
      // posStart = event.touches[0].pageY; //获取起点坐标
      // that.showBlackBoxSpeak();
      console.log("开始");
      let that = this;
      that.uploadaudio = 0;
      that.buttonback = true;
      that.buttontext = "松开 结束";
      event.preventDefault();
      posStart = 0;
      posStart = event.touches[0].pageY; //获取起点坐标
      clearTimeout(timeOutEvent); //清除定时器
      timeOutEvent = 0;
      timeOutEvent = setTimeout(function() {
        //recordstatus为false执行长按事件
        if (that.recordstatus == false) {
          that.blackBoxSpeak = true;
          that.blackBoxPause = false;
          console.log("开始长按事件");
          that.recordAudio();
          that.recordstatus = true;
        }
      }, 600); //这里设置定时
    },
    //手释放，如果在500毫秒内就释放，则取消长按事件，此时可以执行onclick应该执行的事件
    gotouchend(event) {
      // console.log("结束");
      // let that = this;
      // event.preventDefault(); //阻止浏览器默认行为
      // posEnd = 0;
      // posEnd = event.changedTouches[0].pageY; //获取终点坐标
      // that.initStatus();
      // if (posStart - posEnd < 200) {
      //   alert("发送成功");
      //   that.showBlackBoxNone();
      // } else {
      //   alert("取消发送");
      //   that.showBlackBoxNone();
      // }
      console.log("结束");
      let that = this;
      event.preventDefault(); //阻止浏览器默认行为
      posEnd = 0;
      posEnd = event.changedTouches[0].pageY; //获取终点坐标
      that.initStatus();
      clearTimeout(timeOutEvent);
      if (timeOutEvent != 0) {
        //这里写要执行的内容（尤如onclick事件）
        if (that.recordstatus == true) {
          console.log("结束长按事件");
          if (posStart - posEnd < 200) {
            console.log("结束112222");
            that.recordFinish();
            that.recordstatus = false; //结束重置为false
            that.showBlackBoxNone();
            console.log("结束发送");
          } else {
            that.recordFinish();
            console.log("取消发送");
            that.recordstatus = false;
            that.showBlackBoxNone();
          }
        } else {
          console.log("结束单击事件，不做操作");
        }
      } else {
        that.recordstatus = false; //结束重置为false
        that.recordFinish();
        console.log("单击事件1");
      }
    },
    //如果手指有移动，则取消所有事件，此时说明用户只是要移动而不是长按
    gotouchmove(event) {
      console.log("离开");
      let that = this;
      // clearTimeout(timeOutEvent); //清除定时器
      // that.recordFinish();
      event.preventDefault(); //阻止浏览器默认行为
      posMove = event.targetTouches[0].pageY; //获取滑动实时坐标
      if (posStart - posMove < 200) {
        console.log("离开112222");
        //清除定时器

        //隐藏录音 显示暂停
        that.showBlackBoxSpeak();
      } else {
        that.uploadaudio = 1;
        //显示录音 隐藏暂停

        console.log("dsdas");
        that.showBlackBoxPause();
      }
    },
    //初始化状态
    initStatus() {
      var that = this;
      that.buttontext = "按住 说话";
      //全部隐藏
      that.showBlackBoxNone();
    },

    //显示录音 隐藏暂停
    showBlackBoxSpeak() {
      var that = this;
      that.buttontext = "松开 结束";
      that.blackBoxSpeak = true;
      that.blackBoxPause = false;
      that.buttonback = true;
    },

    //隐藏录音 显示暂停
    showBlackBoxPause() {
      var that = this;
      that.buttontext = "松开手指，取消发送";
      that.blackBoxSpeak = false;
      that.blackBoxPause = true;
      that.buttonback = true;
    },

    //隐藏录音
    showBlackBoxNone() {
      var that = this;
      that.buttonback = false;
      that.blackBoxSpeak = false;
      that.blackBoxPause = false;
    },
    //开始录音
    recordAudio() {
      console.log("开始录音");
      var that = this;
      var src = that.recordFile;
      that.mediaRec = new Media(src, that.onSuccess, that.onError);
      // Record audio
      that.mediaRec.startRecord();
      // Stop recording after 10 sec
      that.recTime = 0;
      var recInterval = setInterval(function() {
        console.log("执行录音");
        that.recTimerecTime = that.recTime + 1;
        if (that.recTime >= that.recTimeMax) {
          clearInterval(recInterval);
          that.mediaRec.stopRecord();
          that.mediaRec.release();
        }
      }, 1000);
    },
    onSuccess(mediaFiles) {
      var that = this;
      console.log("录制成功文件", mediaFiles);
      console.log("录制成功文件", that.mediaRec.getDuration());

      console.log("录音装", that.recordstatus);
      console.log("录音成功", this.recordFile);
      console.log(that.mediaRec);
      // that.playAudio(that.recordFile);
      if (that.uploadaudio == 0) {
        that.uploadAudio();
      } else {
        console.log("不发送语音");
      }
    },
    onError(error) {
      console.log("录音失败", this.recordFile);
      console.log(error);
      alert("code: " + error.code + "\n" + "message: " + error.message + "\n");
    },
    //录音完成
    recordFinish() {
      var that = this;
      that.recTime = that.recTimeMax;
      console.log("录音完成");
    },
    //播放audio
    playAudio(url) {
      var that = this;
      // Play the audio file at url

      console.log("播放录音内容", url);
      my_media = new Media(
        url,
        // success callback
        function() {
          console.log("playAudio():Audio Success");
        },
        // error callback
        function(err) {
          console.log("playAudio():Audio Error: " + err);
        },
        function(code) {}
      );
      // Play audio
      my_media.play;

      // my_media.release();
    },
    //上传
    uploadAudio() {
      var that = this;
      console.log("录音上传");
      var service = `${that.$basePath}?service=App.ChannelManage.UploadAudio&api=96`;
      var win = function(r) {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
        // console.log("response", r.response.data);
        that.GetHistoryList();
        var res = r.response;
        if (typeof res == "string") {
          res = eval("(" + res + ")");
        }
        console.log("res", res);
        if (typeof res.data == "string") {
          res.data = eval("(" + res.data + ")");
        }
        console.log("res.data", res.data);

        console.log("socket3", that.global.ws);
        if (that.global.ws && that.global.ws.readyState == 1) {
          console.log("发送信息");
          var msg = {
            audio_path: res.data.path,
            channel_id: that.channelId,
            token: that.token,
            user_id: that.user_id,
            type: "intercom",
            seconds: res.data.seconds
          };
          console.info("audio", msg);
          msg = JSON.stringify(msg);
          that.global.ws.send(msg);
        }
      };

      var fail = function(error) {
        console.log("录音上传失败");
        alert("An error has occurred: Code = " + error.code);
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
      };

      var options = new FileUploadOptions();
      options.fileKey = "file";
      options.fileName = that.recordFile;
      options.mimeType = "audio/wav";
      //上传参数
      var params = {
        token: that.token
      };

      options.params = params;
      var ft = new FileTransfer();
      if (device.platform == "iOS") {
        var path = cordova.file.tempDirectory + that.recordFile;
      } else if (device.platform == "Android") {
        var path = "/sdcard/" + that.recordFile;
      }
      console.log("path", path);
      ft.upload(path, encodeURI(service), win, fail, options);
    }
  }
};
</script>
<style lang="less" scoped>
@import "../../assets/css/communicate";
</style>